package org.JWCB.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.JWCB.common.core.constants.HttpConstants;
import org.JWCB.common.core.constants.UserConstants;
import org.JWCB.common.core.utils.ThreadLocalUtil;
import org.JWCB.common.security.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);
    @Autowired
    private TokenService tokenService;


    @Value("${jwt.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if(token == null) {
            return true;
        }
        Long userId = tokenService.getUserId(token,secret);
        String userKey = tokenService.getLoginKey(token,secret);
        // 放入ThreadLocal,后续使用
        ThreadLocalUtil.set(UserConstants.USER_ID,userId);
        ThreadLocalUtil.set(UserConstants.USER_KEY,userKey);
        tokenService.extendToken(token,secret);
        return true;
    }


    /**
     * 从请求头中获取token
     * @param request 请求
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(HttpConstants.TOKEN_PREFIX,StrUtil.EMPTY);
        }
        return token;
    }


    /**
     * 请求处理之后清除ThreadLocal的数据,防止内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
